﻿using System.Collections;
using System.Web.Routing;

namespace Travel.MVC
{
    /// <summary>
    /// 路由字典工具
    /// </summary>
    public static class RouteValueDictionaryExtentions
    {
        /// <summary>
        /// 转换成路由字典
        /// </summary>
        /// <param name="s">集合</param>
        /// <param name="key">在url中的名称</param>
        /// <returns>路由字典</returns>
        public static RouteValueDictionary ToRouteValueDictionary(this IEnumerable s, string key)
        {
            var dic = new RouteValueDictionary();
            int i = 0;
            foreach (var item in s)
            {
                dic.Add(string.Format("{0}[{1}]", key, i), item);
                i++;
            }

            return dic;
        }

        /// <summary>
        /// 实体转换成路由字典
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="model">实体</param>
        /// <returns>
        /// 路由字典
        /// </returns>
        public static RouteValueDictionary ToRouteValueDictionary<T>(T model) where T : class, new()
        {
            var dic = new RouteValueDictionary();
            var type = typeof(T);
            ////遍历所有属性
            foreach (var prop in type.GetProperties())
            {
                object value = prop.GetValue(model, null);
                if (prop.PropertyType.IsArray)
                {
                    if (value != null)
                    {
                        int i = 0;
                        foreach (var item in (IEnumerable)prop.GetValue(model, null))
                        {
                            dic.Add(string.Format("{0}[{1}]", prop.Name, i), item);
                        }
                    }
                }
                else if (prop.PropertyType.IsEnum)
                {
                    dic.Add(prop.Name, (int)value);
                }
                else
                {
                    dic.Add(prop.Name, value);
                }
            }

            return dic;
        }
    }
}